/**
 * Created by Rolle on 2016/11/25.
 */

var net = require('net');
var formidable = require('formidable');
// 引用模型
var MLUser = require('../models/YJ').MLUsers;
var MLGrouping = require('../models/YJ').MLGrouping;
var MLAddFriend = require('../models/YJ').MLAddFriend;
var MLFriends = require('../models/YJ').MLFriends;




// MLGrouping.create({
//     name: "我的好友",
// }).then(function(result){
//     console.log('inserted XiaoMing ok');
// }).catch(function(err){
//     console.log('inserted XiaoMing error');
//     console.log(err.message);
// });
// MLGrouping.create({
//     name: "我的医生",
// }).then(function(result){
//     console.log('inserted XiaoMing ok');
// }).catch(function(err){
//     console.log('inserted XiaoMing error');
//     console.log(err.message);
// });
// //添加用户
// for (var i = 103295 ; i <103594 ; i++ ){
//     //生成随机数
//     var chars = [
//         'http://img78.nipic.com/file/20161115/11284670_202303612036_1.jpg','http://img78.nipic.com/file/20161115/11284670_202303612036_1.jpg',
//         'http://img78.nipic.com/file/20161115/11284670_202303612036_1.jpg','http://img78.nipic.com/file/20161116/11284670_192106378033_1.jpg',
//         'http://img78.nipic.com/file/20161102/11284670_193225201000_1.jpg','http://img78.nipic.com/file/20161113/20545741_153538580001_1.jpg',
//         'http://img78.nipic.com/file/20161108/9448607_154724790000_1.jpg','http://img78.nipic.com/file/20161113/11284670_162501088000_1.jpg',
//         'http://img22.nipic.com/20101029/4702648_173747072457_1.jpg','http://img19.nipic.com/20100923/1764057_132633954468_1.jpg','http://img19.nipic.com/20100923/1764057_095016988746_1.jpg'];
//     var id = Math.ceil(Math.random()*chars.length);
//
//     var ss = chars[id]
//     MLUser.create({
//         name: i,
//         userHead: ss == null ?'http://img78.nipic.com/file/20161115/11284670_202303612036_1.jpg':ss,
//         addUserType: id,
//     }).then(function(result){
//         console.log('inserted XiaoMing ok');
//     }).catch(function(err){
//         console.log('inserted XiaoMing error');
//         console.log(err.message);
//     });
// }


/**********************好友操作*************************/
//添加好友
exports.doAddFriends = function (req, res, next) {
    //得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        console.log(fields)
        //情况A发出加B的请求,B发出加A的请求时
        //A->B
        //B->A
        //如果一方同意,则这里addType(添加状态)都为1
        //如果一方删除,则删除方该条数据addType(添加状态)都为0,被删除方该条数据删除,
        /*****************************************************************/
        //查询数据库中是否有该条添加数据
        MLAddFriend.findAll({
            where: {
                addUserId: fields.addUserId,
                beAddUserId: fields.beAddUserId
            }
        }).then(function (result) {
            if (result.length == 0) {//A+b没有数据
                // 查询B+A是否有数据,如果有数据则添加成功,如果没有则添加这条数据
                MLAddFriend.findAll({
                    where: {
                        addUserId: fields.beAddUserId,
                        beAddUserId: fields.addUserId
                    }
                }).then(function (result) {
                    if (result.length == 0) {//没有数据,添加该条数据
                        MLAddFriend.create({
                            addUserId: fields.addUserId ,
                            beAddUserId:fields.beAddUserId,
                            addType:0,
                            isRead:0
                        }).then(function(result){
                            res.send({
                                'isSucceed' : '800',
                                'msg' : '好友请求发送成功'
                            });
                        }).catch(function(err){
                            console.log(err)
                            res.send({
                                'isSucceed' : '200',
                                'msg' : '数据库错误'
                            });
                        });
                    }else {//有数据添加到好友列表中,并修改状态,提示添加成功
                        //修改addFriend表中的添加状态
                        MLAddFriend.update({
                            addType:1,
                        },{
                            where:{
                                addUserId: fields.beAddUserId,
                                beAddUserId:fields.addUserId,
                                addType:0,
                            },
                        }).then(function(result){
                            if (result[0] == 0){
                                res.send({
                                    'isSucceed' : '200',
                                    'msg' : '对方已经是您的好友'
                                });
                            }else {
                                //好友表中添加数据
                                var beType = fields.beUserType == 9 ? 2 : 1
                                var userType = fields.userType == 9 ? 2 : 1
                                //添加到好友列表
                                MLFriends.bulkCreate([{
                                    userId:fields.addUserId,
                                    friendGroupingId:beType,
                                    friendId:fields.beAddUserId,
                                    remark:''
                                },{
                                    userId:fields.beAddUserId,
                                    friendGroupingId:userType,
                                    friendId:fields.addUserId,
                                    remark:''
                                }
                                ]).then(function(result){
                                    chaxunhaoyou(fields.addUserId,res)
                                    //发送socket请求
                                    MLUser.update({
                                        ID:fields.beAddUserId
                                    },{
                                        where:{
                                            isSocketFriends:1
                                        }
                                    }).then(function(result){
                                        chaxunhaoyoufanhui(fields.beAddUserId,userSocket[fields.beAddUserId])
                                    });
                                })
                            }
                        }).catch(function(err){
                            res.send({
                                'isSucceed' : '200',
                                'msg' : '数据库错误'
                            });
                        });
                    }
                })
            }else{//A+B有数据,则提示用户等待好友同意,或该用户已经是您的好友了
                res.send({
                    'isSucceed' : '200',
                    'msg' : '等待该用户同意或该用户已是您的好友!!'
                });
            }
        });
    });
};

//查询新朋友
exports.getNewFriends = function (req, res, next) {
    //得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        console.log(fields.userId)
        MLAddFriend.findAll({
            where: { beAddUserId: fields.userId }
        }).then(function (result) {
            var data = JSON.parse(JSON.stringify(result));
            var dataJson = {
                'isSucceed' : '400',
                'data' : []
            };
            console.log(data[0]);
            //异步转同步
            (function iterator(i){
                if(i == data.length){
                    res.send(dataJson);
                    return
                }
                //查找数据库中
                MLUser.findAll({
                    where: { id: data[i].addUserId }
                }).then(function (user) {
                    var sss = JSON.parse(JSON.stringify(user[0]));
                    var userJson = {
                        ID : sss.ID.replace(/\b(0+)/gi,""),
                        NICK_NAME : sss.NICK_NAME,
                        USER_TYPE : sss.USER_TYPE,
                        USER_HEAD : sss.USER_HEAD
                    }
                    console.log(userJson);
                    var oneJson = {};
                    oneJson.id = data[i].id;
                    oneJson.addUser = userJson;
                    oneJson.isRead = data[i].isRead;
                    oneJson.addType = data[i].addType;
                    dataJson.data.push(oneJson)
                    iterator(i+1)
                })
            })(0);
        })
    });
};


//删除好友
exports.doDeleteFriends = function (req, res, next) {
    //得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        console.log('删除好友:'+fields);
    });
};

//查询好友
exports.doMyFriends = function (req, res, next) {
    //得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        var dataJson = {
            'isSucceed' : '400',
            'data' : {
                doctorUsers:[],
                friendUsers:[]
            }
        };
        MLFriends.findAll({
            where: {
                userId: fields.userId,
                friendGroupingId:2
            }
        }).then(function (result) {
            var data = JSON.parse(JSON.stringify(result));
            //查询医生列表
            (function iterator(i){
                if(i == data.length){
                    return
                }
                //查找数据库中
                MLUser.findAll({
                    where: { id: data[i].friendId }
                }).then(function (user) {
                    var user = JSON.parse(JSON.stringify(user[0]));
                    var userJson = {
                        id: user.ID.replace(/\b(0+)/gi,""),
                        name: user.NICK_NAME,
                        userHead: user.USER_HEAD,
                        addUserType: user.USER_TYPE,
                        remark:null
                    }
                    userJson.remark = (data[i].remark == null ? '' : data[i].remark)
                    dataJson.data.doctorUsers.push(userJson)
                    iterator(i+1)
                })
            })(0);

            //查询好友
            MLFriends.findAll({
                where: {
                    userId: fields.userId,
                    friendGroupingId:1
                }
            }).then(function (result) {
                var data = JSON.parse(JSON.stringify(result));
                (function iterator(i){
                    if(i == data.length){
                        res.send(dataJson);
                        return
                    }
                    //查找数据库中
                    MLUser.findAll({
                        where: { id: data[i].friendId }
                    }).then(function (user) {
                        var user = JSON.parse(JSON.stringify(user[0]));
                        var userJson = {
                            id: user.ID.replace(/\b(0+)/gi,""),
                            name: user.NICK_NAME,
                            userHead: user.USER_HEAD,
                            addUserType: user.USER_TYPE,
                            remark:null
                        }
                        userJson.remark = (data[i].remark == null ? '' : data[i].remark)
                        dataJson.data.friendUsers.push(userJson)
                        iterator(i+1)
                    })
                })(0);
            })
        })
    });
};

//设置备注
exports.doFriendsNote = function (req, res, next) {
    //得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        console.log(fields);
        MLFriends.update({
            remark:fields.remark
        },{
            where:{
                userId:fields.userId,
                friendId:fields.friendId
            }
        }).then(function(result){
            //返回删除后的好友列表
            chaxunhaoyou(fields.userId,res)
        });
    });
};

//删除好友
exports.deleteFriend = function (req, res, next) {
    //得到用户填写的东西
    var form = new formidable.IncomingForm();
    form.parse(req, function (err, fields, files) {
        //删除好友
        MLFriends.destroy({where:{userId:fields.userId,friendId:fields.friendId}}).then(function(result){
            MLFriends.destroy({where:{userId:fields.friendId,friendId:fields.userId}}).then(function(result){
                //返回删除后的好友列表
                chaxunhaoyou(fields.userId,res)
                //长连接推送更新好友列表消息给fields.friendId的用户
            }).catch(next);
        }).catch(next);
    })
}


//socket查询用户是否发送socket
exports.isSocket = function (connection,id) {
    //查找数据库中
    MLUser.findAll({
        where: { ID: id}
    }).then(function (user,err) {
        if (err != null){
            console.log(err)
        }
        console.log(JSON.parse(JSON.stringify(user[0])))
    })
}

//socket操作
exports.socketAllData = function (userId,socket,socketType) {
    if (socketType == 0){//新好友列表接收成功,修改数据库isSocketFriends字段
        MLUser.update({
            isSocketFriends : 0
        },{
            where:{
                ID: userId,
            },
        }).then(function(result){

        })
    }else if (socketType == 1){//用户连接,查询是否需要更新好友列表
        var dataJson = {
            'isSucceed' : '400',
            'data' : {
                doctorUsers:[],
                friendUsers:[]
            }
        };
        MLFriends.findAll({
            where: {
                userId: userId,
                friendGroupingId:2
            }
        }).then(function (result) {
            var data = JSON.parse(JSON.stringify(result));
            //查询医生列表
            (function iterator(i){
                if(i == data.length){
                    return
                }
                //查找数据库中
                MLUser.findAll({
                    where: { id: data[i].friendId }
                }).then(function (user) {
                    var user = JSON.parse(JSON.stringify(user[0]));
                    var userJson = {
                        id: user.ID.replace(/\b(0+)/gi,""),
                        name: user.NICK_NAME,
                        userHead: user.USER_HEAD,
                        addUserType: user.USER_TYPE,
                        remark:null
                    }
                    userJson.remark = (data[i].remark == null ? '' : data[i].remark)
                    dataJson.data.doctorUsers.push(userJson)
                    iterator(i+1)
                })
            })(0);
            //查询好友
            MLFriends.findAll({
                where: {
                    userId: userId,
                    friendGroupingId:1
                }
            }).then(function (result) {
                var data = JSON.parse(JSON.stringify(result));
                (function iterator(i){
                    if(i == data.length){
                        //向客户端写入数据
                        console.log(userId);
                        var str = JSON.stringify(dataJson)
                        socket.write(str);
                        return;
                    }
                    //查找数据库中
                    MLUser.findAll({
                        where: { id: data[i].friendId }
                    }).then(function (user) {
                        var user = JSON.parse(JSON.stringify(user[0]));
                        var userJson = {
                            id: user.ID.replace(/\b(0+)/gi,""),
                            name: user.NICK_NAME,
                            userHead: user.USER_HEAD,
                            addUserType: user.USER_TYPE,
                            remark:null
                        }
                        userJson.remark = (data[i].remark == null ? '' : data[i].remark)
                        dataJson.data.friendUsers.push(userJson)
                        iterator(i+1)
                    })
                })(0);
            })
        })
    }
}

function chaxunhaoyou(userId,res) {
    var dataJson = {
        'isSucceed' : '400',
        'data' : {
            doctorUsers:[],
            friendUsers:[]
        }
    };
    MLFriends.findAll({
        where: {
            userId: userId,
            friendGroupingId:2
        }
    }).then(function (result) {
        var data = JSON.parse(JSON.stringify(result));
        //查询医生列表
        (function iterator(i){
            if(i == data.length){
                return
            }
            //查找数据库中
            MLUser.findAll({
                where: { id: data[i].friendId }
            }).then(function (user) {
                var user = JSON.parse(JSON.stringify(user[0]));
                var userJson = {
                    id: user.ID.replace(/\b(0+)/gi,""),
                    name: user.NICK_NAME,
                    userHead: user.USER_HEAD,
                    addUserType: user.USER_TYPE,
                    remark:null
                }
                userJson.remark = (data[i].remark == null ? '' : data[i].remark)
                dataJson.data.doctorUsers.push(userJson)
                iterator(i+1)
            })
        })(0);

        //查询好友
        MLFriends.findAll({
            where: {
                userId: userId,
                friendGroupingId:1
            }
        }).then(function (result) {
            var data = JSON.parse(JSON.stringify(result));
            (function iterator(i){
                if(i == data.length){
                    res.send(dataJson);
                    return
                }
                //查找数据库中
                MLUser.findAll({
                    where: { id: data[i].friendId }
                }).then(function (user) {
                    var user = JSON.parse(JSON.stringify(user[0]));
                    var userJson = {
                        id: user.ID.replace(/\b(0+)/gi,""),
                        name: user.NICK_NAME,
                        userHead: user.USER_HEAD,
                        addUserType: user.USER_TYPE,
                        remark:null
                    }
                    userJson.remark = (data[i].remark == null ? '' : data[i].remark)
                    dataJson.data.friendUsers.push(userJson)
                    iterator(i+1)
                })
            })(0);
        })
    })
}

function chaxunhaoyoufanhui(userId,socket) {
    var dataJson = {
        'isSucceed' : '400',
        'data' : {
            doctorUsers:[],
            friendUsers:[]
        }
    };
    MLFriends.findAll({
        where: {
            userId: userId,
            friendGroupingId:2
        }
    }).then(function (result) {
        var data = JSON.parse(JSON.stringify(result));
        //查询医生列表
        (function iterator(i){
            if(i == data.length){
                return
            }
            //查找数据库中
            MLUser.findAll({
                where: { id: data[i].friendId }
            }).then(function (user) {
                var user = JSON.parse(JSON.stringify(user[0]));
                var userJson = {
                    id: user.ID.replace(/\b(0+)/gi,""),
                    name: user.NICK_NAME,
                    userHead: user.USER_HEAD,
                    addUserType: user.USER_TYPE,
                    remark:null
                }
                userJson.remark = (data[i].remark == null ? '' : data[i].remark)
                dataJson.data.doctorUsers.push(userJson)
                iterator(i+1)
            })
        })(0);
        //查询好友
        MLFriends.findAll({
            where: {
                userId: userId,
                friendGroupingId:1
            }
        }).then(function (result) {
            var data = JSON.parse(JSON.stringify(result));
            (function iterator(i){
                if(i == data.length){
                    //向客户端写入数据
                    console.log(userId);
                    var str = JSON.stringify(dataJson)
                    userSocket[userId].write(str);
                    return;
                }
                //查找数据库中
                MLUser.findAll({
                    where: { id: data[i].friendId }
                }).then(function (user) {
                    var user = JSON.parse(JSON.stringify(user[0]));
                    var userJson = {
                        id: user.ID.replace(/\b(0+)/gi,""),
                        name: user.NICK_NAME,
                        userHead: user.USER_HEAD,
                        addUserType: user.USER_TYPE,
                        remark:null
                    }
                    userJson.remark = (data[i].remark == null ? '' : data[i].remark)
                    dataJson.data.friendUsers.push(userJson)
                    iterator(i+1)
                })
            })(0);
        })
    })
}